<?php
##############################################
#
#   后台公共基础类
# @ Time : 2016-12-22 - 下午11:45:28
# @ Author : JiangYongWei <1085562810@qq.com>
# @ Encoding : UTF-8 language : PHP
#
##############################################

namespace Admin\Model;
use Think\Model;
use Admin\Model\Data;

class AdminBaseModel extends Model{
	
	protected $tableName = 'config';
	
	public function __construct($tableName=''){
		//初始化数据库对象
		if(!empty($tableName)){
			$this -> tableName = $tableName;
		}
		parent::__construct($this -> tableName);
	}
	
	/**
	 * 获取全部菜单
	 * @param  string $type tree获取树形结构 level获取层级结构
	 * @return array       	结构数据
	 */
	public function getTreeData($type='tree', $order='', $name='name', $child='id', $parent='pid'){
		// 判断是否需要排序
		if(empty($order)){
			$data = $this -> select();
		}else{
			$data = $this -> order('order_number is null,'.$order) -> select();
		}

		// 获取树形或者结构数据
		if($type == 'tree'){
			$data = Data::tree($data, 'name', 'id', 'pid');
		}else if($type="level"){
			$data = Data::channelLevel($data, 0, '&nbsp;', 'id');
			// 显示有权限的菜单
			$auth = new \Think\Auth();
				
			foreach($data as $k => $v)
			{
				if ($auth -> check($v['mca'], $_SESSION['user']['id']))
				{
					foreach($v['_data'] as $m => $n)
					{
						if(!$auth -> check($n['mca'], $_SESSION['user']['id']))
						{
							unset($data[$k]['_data'][$m]);
						}
					}
				}
				else
				{
					// 删除无权限的菜单
					unset($data[$k]);
				}
			}
		}
		return $data;
	}
	
	/**
	 * 获取全部数据
	 * @param  string $type  tree获取树形结构 level获取层级结构
	 * @param  string $order 排序方式
	 * @return array         结构数据
	 */
	public function getTreeDataLevel($type='tree',$order='',$name='name',$child='id',$parent='pid'){
		// 判断是否需要排序
		if(empty($order)){
			$data = $this -> select();
		}else{
			$data = $this -> order($order.' is null,'.$order) -> select();
		}
		// 获取树形或者结构数据
		if($type == 'tree'){
			$data = Data::tree($data, $name, $child, $parent);
		}else if($type == "level"){
			$data = Data::channelLevel($data, 0, '&nbsp;', $child, 'p_id');
		}
		return $data;
	}
	
	/**
	 * 添加数据
	 * @param  array $data  添加的数据
	 * @return int          新增的数据id
	 */
	public function addData($data){
		// 去除键值首尾的空格
		foreach ($data as $k => $v) {
			$data[$k] = trim($v);
		}
		$id = $this -> add($data);
		return $id;
	}
	
	/**
	 * 修改数据
	 * @param   array   $map    where语句数组形式
	 * @param   array   $data   数据
	 * @return  int     操作是否成功
	 */
	public function editData($map, $data){
		// 去除键值首位空格
		foreach ($data as $k => $v) {
			$data[$k] = trim($v);
		}
		$result = $this -> where($map) -> save($data);
		return $result;
	}
	
	/**
	 * 删除数据
	 * @param   array   $map    where语句数组形式
	 * @return  boolean         操作是否成功
	 */
	public function deleteData($map){
		if (empty($map)) {
			die('where为空的危险操作');
		}
		$result = $this -> where($map) -> delete();
		return $result;
	}
	
	/**
	 * 数据排序
	 * @param  array $data   数据源
	 * @param  string $id    主键
	 * @param  string $order 排序字段
	 * @return boolean       操作是否成功
	 */
	public function orderData($data, $id='id', $order='order_number'){
		foreach ($data as $k => $v){
			$v = empty($v) ? null : $v;
			$this -> where(array($id => $k)) -> save(array($order => $v));
		}
		return true;
	}
	
	/**
	 * 获取分页数据
	 * @param  subject  $model  model对象
	 * @param  array    $map    where条件
	 * @param  string   $order  排序规则
	 * @param  integer  $limit  每页数量
	 * @param  integer  $field  $field
	 * @return array            分页数据
	 */
	public function getPage($model,$map,$order='',$limit=10,$field=''){
		$count = $model -> where($map) -> count();
		$page = new_page($count, $limit);
		// 获取分页数据
		if (empty($field)) {
			$list = $model -> where($map) -> order($order) -> limit($page->firstRow.','.$page->listRows)
						 ->select();
		}else{
			$list = $model -> field($field) -> where($map) -> order($order) -> limit($page->firstRow.','.$page->listRows)
			->select();
		}
		$data = array('data' => $list, 'page' => $page -> show());
		return $data;
	}
	
	/**
	  * 上传图片
	  * @param number $width 缩略图宽带
	  * @param number $height 缩略图高度
	  * @param string $dirname 保存路径 "logo/"
	  * @date 2017年7月26日 - 下午12:02:20
	  * @author JiangYongWei
	 */
 	public static function upload($width=160, $height=160, $dirname){
	    $upload = new \Think\Upload();// 实例化上传类
	    $upload->maxSize   =     3145728 ;// 设置附件上传大小
	    $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
	    $upload->rootPath  =     './Upload/'; // 设置附件上传根目录
	    $upload->savePath  =     $dirname; // 设置附件上传（子）目录   如:'goods/'
	    // 上传文件
	    $info   =   $upload->upload();
	    /* var_dump($info);
	     exit; */
	    if(!$info) {// 上传错误提示错误信息
	        exit($upload->getError());
	    }else{// 上传成功
	        $image = new \Think\Image();
	        foreach ($info as $key => $value) {
	            $image->open('./Upload/'.$value['savepath'].$value['savename']);
	            $file_name = time().rand(0,999).uniqid();
	            $image->thumb($width, $height)->save('./Upload/'.$value['savepath'].$file_name.'_thumb_'.$width.'_'.$height.'.'.$value['ext']);
	            //@unlink($_SERVER['DOCUMENT_ROOT'].substr(__APP__, 1).'/Upload/'.$value['savepath'].$value['savename']);
	            @unlink($_SERVER['DOCUMENT_ROOT'].'/Upload/'.$value['savepath'].$value['savename']);
	            $work_img[$key] = '/Upload/' . $value['savepath'] . $file_name.'_thumb_'.$width.'_'.$height.'.'.$value['ext'];
	        }
	        /*  var_dump($work_img);
	         exit; */
	        return $work_img; // 序列化
	    }
	}
        
        public function uploadImg(){
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     3145728 ;// 设置附件上传大小
        $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath  =     './Upload/'; // 设置附件上传根目录
        $upload->savePath  =     ''; // 设置附件上传（子）目录
        // 上传文件
        $info   =   $upload->upload(array($_FILES['more_img']));
        if(!$info) {// 上传错误提示错误信息
            exit($upload->getError());
        }else{// 上传成功
            $image = new \Think\Image();
            foreach ($info as $key => $value) {
                $image->open('./Upload/'.$value['savepath'].$value['savename']);
                $file_name = time().rand(0,999).uniqid();
                $image->save('./Upload/'.$value['savepath'].'L'.$file_name.'.jpg');
                $image->thumb(580, 440)->save('./Upload/'.$value['savepath'].'M'.$file_name.'.jpg');
                $image->thumb(110,70)->save('./Upload/'.$value['savepath'].'S'.$file_name.'.jpg');
                @unlink($_SERVER['DOCUMENT_ROOT'].substr(__APP__, 1).'/Upload/'.$value['savepath'].$value['savename']);
                $work_img['L'][$key] = '/Upload/' . $value['savepath'] .'L'. $file_name . '.jpg';
                $work_img['M'][$key] = '/Upload/' . $value['savepath'] .'M'. $file_name . '.jpg';
                $work_img['S'][$key] = '/Upload/' . $value['savepath'] .'S'. $file_name . '.jpg';
            }
            return $work_img; // 序列化
        }
    }
}